﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace AlbumDesigner.Helpers
{
    // Per session logging
    public class LoggerHelper
    {
        public const string LOG_KEY = "logfilename";
        public const string LOG_DIR = "userLogs/";

        public static string GenerateLogFileName()
        {
            string filename = string.Format("log-{0:yyyy-MM-dd_hh-mm-ss-tt}.txt", DateTime.Now);
            return filename;
        }

        public static DateTime TimeSince1970ToDateTime(Int64 msSince1970)
        {
            DateTime dt1970 = new DateTime(1970, 1, 1);
            dt1970 = dt1970.AddMilliseconds(msSince1970);
            return dt1970;
        }

        public static void AddLine(string level, string category, string timestamp, string message)
        {
            string time = TimeSince1970ToDateTime(Int64.Parse(timestamp)).ToString();
            string line = time + " " + level + " [" + category + "] " + message;

            string filename = LogFileName();
            string fullname = HttpContext.Current.Server.MapPath("~/" + LOG_DIR + filename);

            // Append line to file
            StreamWriter SW = File.AppendText(fullname);
            SW.WriteLine(line);
            SW.Close();
        }

        public static string LogFileName()
        {
            if (HttpContext.Current.Session != null)
            {
                string filename = HttpContext.Current.Session[LOG_KEY] as string;

                if (filename == null)
                {
                    filename = GenerateLogFileName();
                    HttpContext.Current.Session[LOG_KEY] = filename;
                }

                return filename;
            }
            else
            {
                return null;
            }
        }

        
    }

}